<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\Province;
use Illuminate\Support\Facades\Auth;
use App\Repositories\ProvinceRepository;
use App\Http\Requests\Common\Province\ShowRequest;
use App\Http\Requests\Common\Province\QueryResource;
use App\Http\Requests\Common\Province\ProvinceCreate;
use App\Http\Requests\Common\Province\ProvinceUpdate;
use App\Http\Requests\Common\Province\ProvinceDestroy;

class ProvinceController extends Controller
{
    protected $provinceRepository;

    /**
     * ProvincesController constructor.
     * @param ProvinceRepository $provinceRepository
     */
    public function __construct(
        ProvinceRepository $provinceRepository
    )
    {
        $this->provinceRepository = $provinceRepository;
    }

    /**
     * 获取省份资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $area_id = $request->get('area_id', false);
        $provinces = $this->provinceRepository->getProvinces($area_id);
        return success($provinces);
    }

    /**
     * 获取省份详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, Province $province)
    {
        return success($province);
    }


    /**
     * 创建省份
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ProvinceCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(ProvinceCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $provinces = $this->provinceRepository->create($attributes);
        return stored($provinces);
    }

    /**
     * 更新省资源
     *
     * Date: 2018/05/11
     * @author Tenny
     * @param ProvinceUpdate $request
     * @param province $province
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(ProvinceUpdate $request, Province $province)
    {
        $provincesAttr = $request->only([
            'province_name',
            'sort',
        ]);
        $province->update($provincesAttr);
        return updated($province);
    }

    /**
     * 删除 省 资源
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ProvinceDestroy $request
     * @param Province $province
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(ProvinceDestroy $request, Province $province)
    {
        $force = $request->get('force');
        $force ? $province->delete() : $province->forceDelete();
        return deleted();
    }
}
